#include "queue.h"

Queue *newQueue(int capacity)
{
    if(capacity <=0)
    {
        return NULL;
    }
    int *arr = (int *)malloc(sizeof(int) *capacity);
    if(!arr)
    {
        printf("malloc arr fail\r\n");
        return NULL;
    }
    Queue *queue = (Queue*)malloc(sizeof(Queue));
    if(!queue)
    {
        printf("malloc arr fail\r\n");
        return NULL;
    }
    queue->arr = arr;
    queue->capacity = capacity;
    queue->headIndex = -1;
    queue->tailIndex = -1;
    queue->size = 0;
    return queue;
}

int push(Queue *queue,int num)
{
    if(isFull(queue))
    {
        printf("queue is full\r\n");
        return -1;
    }
    if(queue->size == 0)
    {
        queue->headIndex = 0;
        queue->tailIndex = 0;
    }
    else
    {
        queue->tailIndex = (queue->tailIndex + 1) % (queue->capacity);
    }
    queue->arr[queue->tailIndex] = num;
    queue->size++;
    return 0;
}

int take(Queue *queue,int *ele)
{
    if(isEmpty(queue))
    {
        printf("queue is empty\r\n");
        return -1;
    }
    *ele = queue->arr[queue->headIndex];
    if(queue->size == 1)
    {
        queue->headIndex = -1;
        queue->tailIndex = -1;
    }
    else
    {
        queue->headIndex = (queue->headIndex + 1) % (queue->capacity);
    }
    queue->size--;
    return 0;
}

int isFull(Queue *queue)
{
    return (queue->tailIndex+1) % queue->capacity == queue->headIndex;
}


int isEmpty(Queue *queue)
{
    return queue->size == 0;
}

void freeQueue(Queue *queue)
{
    if(queue)
    {
        free(queue->arr);
        free(queue);
    }
}

void printfQueue(Queue *queue)
{
    if(!queue)
    {
        return;
    }
    printf("===============queue msg=============\r\n");
    printf("capacity:%d\r\n",queue->capacity);
    printf("headIndex:%d\r\n",queue->headIndex);
    printf("tailIndex:%d\r\n",queue->tailIndex);
    printf("size:%d\r\n",queue->size);
    printf("arr:\r\n",queue->size);
    if(isEmpty(queue))
    {
        return;
    }
    for(int i = queue->headIndex;;i = (i+1)%queue->capacity)
    {
        printf("arr[%d] = %d, ",i,queue->arr[i]);
        if(i == queue->tailIndex)
        {
            break;
        }
    }
    printf("\r\n============================\r\n");
}